import React from 'react';
import { Formik, Form, Field, ErrorMessage, useField } from 'formik';
import * as Yup from 'yup';

const FormikPower = () => {
  const initialValues = { username: '', content: '文本框', color: 'green', password: '', habbies: ['大奶妹'] };
  const handleSubmit = values => console.log(values);
  const schema = Yup.object({
    username: Yup.string().max(15, '超了，傻逼').required('必填啊啊啊啊'),
    password: Yup.string().min(6, '太短了').required('密码必填')
  });

  return (
    <>
      <h1>使用组件的方式构建表单</h1>
      <h3>构建其他表单项 使用as</h3>
      <h5>formik 表单 没有密码框 和 复选框 需要自定义 使用 useField</h5>
      <p>useField: field 存放的值 meta 属性 helper 方法</p>
      <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={schema}>
        <Form>
          <Field name="username" />
          <ErrorMessage name="username" />
          <Field as="textarea" name="content" />
          <Field name="color" as="select">
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
          </Field>
          <MyInput id="myPass" name="password" type="password" placeholder="请输入密码" label="密码" />
          <MyCheckbox value="大奶妹" label="大奶妹" name="habbies" />
          <MyCheckbox value="大长腿" label="大长腿" name="habbies" />
          <MyCheckbox value="气质逼人" label="气质逼人" name="habbies" />
        </Form>
      </Formik>
      <input type="submit" onClick={handleSubmit} />
    </>
  );
};

// 自定义密码框
const MyInput = ({ label, ...props }) => {
  const [field, meta] = useField(props);

  return (
    <div>
      <label htmlFor={props.id}>{label}</label>
      <input {...field} {...props} />
      {meta.touched && meta.error ? <span>{meta.error}</span> : null}
    </div>
  );
};

// 自定义复选框框
const MyCheckbox = ({ label, ...props }) => {
  const [field, meta, helper] = useField(props);
  console.log(field, meta, '----------验证');
  const { value } = meta;
  const { setValue } = helper;

  const handChange = () => {
    const set = new Set(value);
    if (set.has(props.value)) {
      set.delete(props.value);
    } else {
      set.add(props.value);
    }
    setValue([...set]);
  };

  return (
    <>
      <label htmlFor="">
        <input type="checkbox" checked={value.includes(props.value)} {...props} onChange={handChange} /> {label}
      </label>
    </>
  );
};

export default FormikPower;
